package com.pms.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.pms.entity.*;
import com.pms.mapper.*;
import com.pms.rpc.IMemberService;
import com.pms.service.IBillTableService;
import com.pms.util.NuType;
import com.pms.util.NumberUtil;
import com.pms.util.idutil.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 
 *
 * @author zyl
 * @email 517770986@qq.com
 * @date 2017-11-01 11:52:51
 */
@Service
public class BillTableServiceImpl extends ServiceImpl<BillTableMapper,BillTable> implements IBillTableService {
    final SnowFlake worker = new SnowFlake(0,0);
    private IMemberService memberService;
    @Autowired
    public BillTableServiceImpl(
            IMemberService memberService) {
        this.memberService = memberService;
    }
    @Autowired
    private BillTableMapper billTableMapper;
    @Autowired
    private EstateAgencyMapper estateAgencyMapper;
    @Autowired
    private UnitHouseMapper unitHouseMapper;
    @Autowired
    private ChargeTemplateMapper chargeTemplateMapper;
    @Autowired
    private ChargeValueMapper chargeValueMapper;
    @Autowired
    private BillTableDetailMapper billTableDetailMapper;

    @Override
    public MemberInfo queryBymember(Long memberId) {
        MemberInfo member = memberService.queryBymember(memberId);
        return member;
    }

    @Override
    public List<Map<String, Object>> selectBillTables(Wrapper<BillTable> wrapper) {
        return billTableMapper.selectBillTables(wrapper);
    }

    @Override
    public List<BillTable> selectBillTableDetailsByParam(Wrapper<BillTable> wrapper) {
        return billTableMapper.selectBillTableDetailsByParam(wrapper);
    }

    @Override
    @Transactional
    public void addBillTableByTimer() {
        //所需要生成的账单列表
        List<BillTable> btList = new ArrayList<BillTable>();
        //所需要生成的账单详情列表
        List<BillTableDetail> btdList = new ArrayList<BillTableDetail>();
        //获取当前的年月份
        Calendar rightNow = Calendar.getInstance();
        int year = rightNow.get(Calendar.YEAR);
        int month = rightNow.get(Calendar.MONTH)+1;
        //如果当前月份为11月或12月，生成的年份是下一年的物业费账单
        if(month>=11){
            year = year+1;
        }
        Wrapper<EstateAgency> wrapper = new EntityWrapper<EstateAgency>();
        wrapper.eq("agency_state",1);
        wrapper.eq("agency_type",2);
        List<EstateAgency> estateAgencyList = estateAgencyMapper.selectList(wrapper);
        List<Long> spIdList = new ArrayList<Long>();
        for(int i=0;i<estateAgencyList.size();i++){
            EstateAgency ea = estateAgencyList.get(i);
            Long spId = ea.getAgencyId();
            Wrapper<BillTable> wp = new EntityWrapper<BillTable>();
            wp.eq("bill_year",year);
            wp.eq("sp_id",spId);
            Integer count = billTableMapper.selectCount(wp);
            if(count<1){
                spIdList.add(spId);
            }
            if(spIdList.size()>15){
                break;
            }
        }
        for(Long spId:spIdList){
            Wrapper<UnitHouse> wp = new EntityWrapper<UnitHouse>();
            wp.eq("community_id",spId);
            List<UnitHouse> uhList = unitHouseMapper.selectList(wp);
            //判断此物业社区是否生成此年份下的账单
            Wrapper<BillTable> wpBillTable = new EntityWrapper<BillTable>();
            wpBillTable.eq("sp_id",spId);
            wpBillTable.eq("bill_year",year);
            Integer count = billTableMapper.selectCount(wpBillTable);
            if(count>0){
                continue;
            }
            if(uhList.size()>0){
                for(UnitHouse uh:uhList){
                    Double houseProportion = uh.getHouseProportion();//房屋面积
                    Integer isHaveMaster = uh.getIsHaveMaster();//是否 导入户主信息(1-是，2-否)
                    Integer isEstateHouse = uh.getIsEstateHouse();//是否是物业办公室（1-是，2-不是）
                    Integer isHaveChargeTemplate = uh.getIsHavaChargeTemplate();//是否配置物业费模板（2-否，1-是）
                    if(houseProportion==null||isEstateHouse==1||isHaveChargeTemplate==2){
                        continue;
                    }
                    Long chargeTemplateId = uh.getChargeTemplateId();
                    ChargeTemplate chargeTemplate = chargeTemplateMapper.selectById(chargeTemplateId);
                    Wrapper<ChargeValue> wpChargeValue = new EntityWrapper<ChargeValue>();
                    wpChargeValue.eq("charge_template_id",chargeTemplateId);
                    List<ChargeValue> cvList = chargeValueMapper.selectList(wpChargeValue);
                    for(int i=1;i<=12;i++){
                        String billNu = NumberUtil.getNu(NuType.billNu);
                        Double totalFee = new Double(0);
                        //物业费详情
                        for(ChargeValue cv:cvList){
                            Double chargeValue = cv.getChargeValue();//模板值
                            Integer chargeWay = cv.getChargeWay();//费用计算方式(1-建筑面积计算,2-固定费用,3-水电气使用量计算)
                            BigDecimal area = new BigDecimal(houseProportion);
                            BigDecimal value = new BigDecimal(chargeValue);
                            Double fee = null;
                            if(chargeWay==1){
                                fee = value.multiply(area).doubleValue();
                            }else if(chargeWay==2){
                                fee = chargeValue.doubleValue();
                            }
                            BillTableDetail billTableDetail = new BillTableDetail();
                            billTableDetail.setBillNu(billNu);
                            billTableDetail.setBillTableDetailId(worker.nextId());
                            billTableDetail.setPrice(chargeValue);
                            billTableDetail.setTemplateName(cv.getChargeName());
                            billTableDetail.setTemplateValue(uh.getHouseProportion());
                            billTableDetail.setTotalPrice(fee);
                            btdList.add(billTableDetail);
                            totalFee += fee;
                        }
                        //生成账单
                        BillTable bt = new BillTable();
                        bt.setHouseId(uh.getHouseId());
                        bt.setBillName("物业缴费");
                        bt.setBillNu(billNu);
                        bt.setIsPayment(1);
                        bt.setSpId(spId);
                        bt.setBillYear(year);
                        bt.setBillMonth(i);
                        if(i<=3){
                            bt.setBillSeason(1);
                            bt.setBillHalfYear(1);
                        }else if(3<i&&i<=6){
                            bt.setBillSeason(2);
                            bt.setBillHalfYear(1);
                        }else if(i>6&&i<=9){
                            bt.setBillSeason(3);
                            bt.setBillHalfYear(2);
                        }else if(i>9&&i<=12){
                            bt.setBillSeason(4);
                            bt.setBillHalfYear(2);
                        }
                        bt.setCreateTime(new Date());
                        bt.setTotalPrice(totalFee);
                        bt.setBillId(worker.nextId());
                        btList.add(bt);
                    }
                    }
            }
        }
        billTableMapper.addBillTableList(btList);
        billTableDetailMapper.addBillTableDetailList(btdList);
    }
}